/**
 * 
 */
package lt.vin.exaatto.client.ui;

import lt.vin.exaatto.client.events.ChatRemovedHandler;
import lt.vin.exaatto.client.events.ChatSelectedHandler;
import lt.vin.exaatto.client.events.ManagerAddedEvent;
import lt.vin.exaatto.client.events.ManagerAddedHandler;
import lt.vin.exaatto.shared.Chat;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;


/**
 * @author Vincentas
 *
 */
public class ManagersPanel extends BaseContainerWidget<String> implements ChatSelectedHandler, ManagerAddedHandler, ChatRemovedHandler {

	private Chat currentChat;
	
	public ManagersPanel() {
		super("Managers");
		
		textBox.setPlaceholder("Add manager...");
		
		Stat.getHandlerManager().addHandler(ManagerAddedHandler.type, this);
		Stat.getHandlerManager().addHandler(ChatSelectedHandler.type, this);
		Stat.getHandlerManager().addHandler(ChatRemovedHandler.type, this);
	}

	@Override
	public void selectedChat(Chat chat) {
		setCurrentChat(chat);
		setElements(chat.getManagers());
		setVisible(true);
	}

	@Override
	public void newManager(Chat chat, String manager) {
		addElement(manager);
	}

	@Override
	public void removedChat(Chat chat) {
		clear();		
		setVisible(false);
	}

	/* (non-Javadoc)
	 * @see lt.vin.exaatto.client.ui.BaseContainerWidget#onRemoveElement(java.lang.Object)
	 */
	@Override
	public void onRemoveElement(final String manager) {
		Stat.getRpcService().removeChatManager(currentChat.getId(), manager, new AsyncCallback<Void>() {
			
			@Override
			public void onSuccess(Void result) {
				currentChat.removeManager(manager);
				removeElement(manager);				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());				
			}
		});
	}

	@Override
	protected void newTextEntered(final String text) {
		Stat.getRpcService().addChatManager(getCurrentChat().getId(), text, new AsyncCallback<Void>() {
			
			@Override
			public void onSuccess(Void result) {
				getCurrentChat().addManager(text);
				Stat.getHandlerManager().fireEvent(new ManagerAddedEvent(getCurrentChat(), text));
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert(caught.toString());				
			}
		});		
	}

	/**
	 * @return the currentChat
	 */
	public Chat getCurrentChat() {
		return currentChat;
	}

	/**
	 * @param currentChat the currentChat to set
	 */
	public void setCurrentChat(Chat currentChat) {
		this.currentChat = currentChat;
	}
}
